<?php
namespace app\common\model;
use x\Xbase;
class OrderGoods extends Xbase
{

    /**
     * 订单商品列表
     * [lists description]
     * @param  array   $map   [description]
     * @param  integer $o     [description]
     * @param  integer $page  [description]
     * @param  integer $limit [description]
     * @return [type]         [description]
     */
    public function lists($map=[],$o=0,$page=1,$limit=10){
      $w = where($map);
      $order = "";
      switch($o){
        case 1: //综合排序
          $order = "";
          break;
          default:
          $order = "order by fahuo_status desc,id desc";
      }
      $sql = "select * from order_goods $w[0] {$order} ".limit($page,$limit);
      $rs = $this->db->query($sql,$w[1],'',true);
      return $rs;
    }


    /**创建订单
     * @param $user_id 用户ID
     * @param $goods_ids 购物车商品ID数组
     * @param $order_no 订单编号
     * @param $address_id 地址ID
     */
    public  function createOrder($user_id,$goods_ids,$order_no,$address_id){
        //库存判断
        $attr_ids = [];
        foreach ($goods_ids as $k => $v) {
            $attr_ids[] = $k;
        }
        $map = [
          ['and','a.id','in', $attr_ids]
        ];
        $w = where($map);
        $sql = "select a.*,b.title as goods_name,b.pic,b.postage,b.shop_id from goods_price a left join goods b on a.goods_id=b.id " . $w[0];
        $attr_good_list = $this->db->query($sql,$w[1]);

        foreach ($attr_good_list as $k => $v) {
            foreach ($goods_ids as $k1 => $v1) {
                if($v["stock"] < $v1){
                    return $this->setError('库存不足！');
                }
            }
        }
        $pay_total_price = 0;//购物车支付总价
        $address_info = $this->db->query("select * from user_address where id = ? and user_id = ?",[$address_id,$user_id],1);
        if(!$address_info){
            return $this->setError('地址不存在!');
        }

        $alist = $this->getAllAddress();
        //创建订单
        $data = [];
        $total = 0;
        foreach ($attr_good_list as $k => $v) {
            $d = [
                "user_id" => $user_id,
                "goods_price_id" => $v["id"],
                "goods_id" => $v["goods_id"],
                "shop_id" => $v["shop_id"],
                "order_no" => $order_no,
                "title" => $v["goods_name"],
                "goods_price_title" => $v["title"],
                "pic" => $v["pic"],
                "goods_price_price" => $v["price"],
                "sh_name" => $address_info['address_name'],
                "sh_address" => $alist[$address_info['province']] . ' ' . $alist[$address_info['city']] . ' ' . $alist[$address_info['district']] . ' ' . $address_info['address'],
                "sh_phone" => $address_info['address_phone'],
                "nums" => $goods_ids[$v['id']],
                "total_money" => ($v["price"]+$v['postage'])*$goods_ids[$v['id']],
                "create_time" => time(),
            ];
            $data[] = $d;
            $total += $d['total_money'];
        }
        foreach($data as $k=>$v){
            $data[$k]['order_total_money'] = $total;
        }
        $rs = $this->db->insertAll('order_goods',$data);
        if(!$rs){
            return $this->setError('创建订单失败!');
        }else{
            return $rs;
        }
        return $rs;
    }

    //获取子地区名称
    private function getAllAddress(){
        $rs = $this->db->query('select id,name from com_address');
        $map = [];
        foreach ($rs as $key => $value) {
            $map[$value['id']] = $value['name'];
        }
        return $map;
    }

    public function listsinfo($map=[],$o=0,$page=1,$limit=10){
        $w = where($map);
        $order = "";
        switch($o){
          case 1: //综合排序
            $order = "";
            break;
            default:
            $order = "order by a.order_no,a.id desc";
        }
        $sql = "select a.*,concat_ws('',title,'(',goods_price_title,')','X',nums) as goods_title
                  from order_goods as a
                  left join user b on a.user_id=b.id $w[0] {$order} ".limit($page,$limit);
        $rs = $this->db->query($sql,$w[1],'',true);
        return $rs;
    }

    public function groupLists($map=[],$o=0,$page=1,$limit=10){
        $w = where($map);
        $order = "";
        switch($o){
          case 1: //综合排序
            $order = "";
            break;
            default:
            $order = "order by a.id desc";
        }
        $sql = "select a.*,group_concat(concat_ws('',title,'(',goods_price_title,')','X',nums) separator '<br/>') as goods_title,sum(order_total_money) as sum_price
                  from order_goods as a
                  left join user b on a.user_id=b.id $w[0] group by a.order_no {$order} ".limit($page,$limit);
        $rs = $this->db->query($sql,$w[1],'',true);
        return $rs;
    }

    //订单详情
    public function orderInfo($map=[]){
        $w = where($map);
        $sql = "select o.*,u.username from order_goods as o inner join user as u on u.id = o.user_id $w[0]";
        $rs = $this->db->query($sql,$w[1]);
        return $rs;
    }

    /**
     * 下载订单
     * [downOrder description]
     * @param  [type] $nos [description]
     * @param  [type] $eid [description]
     * @return [type]      [description]
     */
    public function downOrder($order_no,$eid){
        $order_no = explode(',',$order_no);
        //查询订单
        $map = [
            ['and','order_no','in',$order_no]
        ];
        $w = where($map);
        $rs = $this->db->query("
        select
            a.*,b.username
        from order_goods as a
            inner join user as b on a.user_id = b.id
        order by a.id desc
        $w[0]",$w[1]);
        // //查询快递
        // $info = $this->db->query('select * from express where id = ?',[$eid],1);
        // foreach ($rs as $k => $v) {
        //     $rs[$k]["kd_name"] = $info['name'];
        // }
        $list = $this->db->query('select * from deploy');
        $temp = [];
        foreach ($list as $k => $v) {
            $temp[$v['name']] = $v['value'];
        }
        foreach ($rs as $k => $v) {
            $rs[$k]['goods_price_title'] = $v['title'] . ' ' . $v['goods_price_title'];
            $rs[$k]['fahuo_name'] = $temp['fahuo_name'];
            $rs[$k]['fahuo_phone'] = $temp['fahuo_phone'];
            $rs[$k]['fahuo_dizhi'] = $temp['fahuo_dizhi'];
            $rs[$k]['fahuo_youbian'] = $temp['fahuo_youbian'];
            $rs[$k]['daishouhuokuan'] = '';
            $rs[$k]['shoujianrenyuobian'] = '';
            $rs[$k]['shoujianrenguhua'] = '';
            $rs[$k]['baojiajine'] = '';
            $rs[$k]['create_time'] = date('Y-m-d H:i:s',$v['create_time']);
        }
        switch ($eid) {
            case '1':
                $title = ['物流单号','会员名称','商品名称','数量','单价','总价','收件人姓名','收件人地址','收件人手机号','发件人姓名','发件人电话','发件人地址','发件人邮编','代收货款','备注','收件人邮编','收件人固话','保价金额','日期'];
                $fields= ['kd_no','username','goods_price_title','nums','goods_price_price','total_money','sh_name','sh_address','sh_phone','fahuo_name','fahuo_phone','fahuo_dizhi','fahuo_youbian','daishouhuokuan','kd_note','shoujianrenyuobian','shoujianrenguhua','baojiajine','create_time'];
                break;
            default:
                $title = ['物流单号','会员名称','商品名称','数量','单价','总价','收件人姓名','收件人地址','收件人手机号','发件人姓名','发件人电话','发件人地址','发件人邮编','代收货款','备注','收件人邮编','收件人固话','保价金额','日期'];
                $fields= ['kd_no','username','goods_price_title','nums','goods_price_price','total_money','sh_name','sh_address','sh_phone','fahuo_name','fahuo_phone','fahuo_dizhi','fahuo_youbian','daishouhuokuan','kd_note','shoujianrenyuobian','shoujianrenguhua','baojiajine','create_time'];
                break;
        }
        $file = com_csv($rs,$title,$fields,'order');
        return $file;
    }

    //申请退款
    public function apply_refund($id){
        $rs = $this->db->find('order_goods',$id);
        if(!$rs){
            return $this->setError('订单不存在!');
        }
        if($rs['pay_status'] != 1 || $rs['fahuo_status'] != 0 || $rs['refund_status'] != 0){
            return $this->setError('该订单不能申请退款!');
        }
        return $this->db->update("order_goods",['refund_status' =>1],['id=?',[$id]]);
    }

    //退款操作
    public function edit_refund($id,$type,$action_user_id){
        $info = $this->db->find('order_goods',$id);
        if(!$info){
            return $this->setError('订单不存在!');
        }
        if($info['refund_status'] != 1 && $info['refund_status'] != 0){
            return $this->setError('该订单不能执行该操作!');
        }
        $rs = 0;
        switch ($type) {
            case 0:
                $rs = $this->db->update('order_goods',['refund_status'=>0],['id=?',[$id]]);
                $msg = "取消退款申请，订单id【".$info['id']."】，编号【".$info['order_no']."】";
                m('Log','xcom')->record($action_user_id, $msg,'admin_user');
                break;
            case 1:
                $rs = $this->db->update('order_goods',['refund_status'=>2],['id=?',[$id]]);
                $rs = m('OrderUmoney','c')->doit($info['user_id'], $action_user_id, 'money', $info['total_money'], "订单退款");
                $msg = "取消订单，订单id【".$info['id']."】，编号【".$info['order_no']."】";
                m('Log','xcom')->record($action_user_id, $msg,'admin_user');
                break;
            case 2:
                $rs = $this->db->update('order_goods',['refund_status'=>2],['id=?',[$id]]);
                $rs = m('OrderUmoney','c')->doit($info['user_id'], $action_user_id, 'money', $info['total_money'], "订单退款");
                $msg = "同意退款申请，订单id【".$info['id']."】，编号【".$info['order_no']."】";
                m('Log','xcom')->record($action_user_id, $msg,'admin_user');
                break;
            default:

                break;
        }
        return $rs;
    }

}
